package com.github_Dididipapa.shortlink.project.Scheduled;

import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.XSlf4j;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @description: redis定时任务
 * @author: dididi_papa
 * @email: mitis1624087624@gmail.com
 * @date: 2025/09/20  15:10
 */
@Component
public class RedisScheduled {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    @Qualifier("RBloom-link")
    private RBloomFilter<String> bloomFilter;
    private static final Logger log = LoggerFactory.getLogger(RedisScheduled.class);


    @Scheduled(cron = "00 00 23 L * ?")
    @Async("taskThreadPool")
    void clearLinkBloomFilter() {
        try {
            stringRedisTemplate.delete("link");
        }
        catch (Exception e) {
            log.error("clearLinkBloomFilter error: {}", e.getMessage());
        }
    }

    @Scheduled(cron = "00 30 23 L * ?")
    @Async("taskThreadPool")
    void addDataToBloomFilter() {
        try {
            stringRedisTemplate.opsForHash().keys("short-link-map").stream()
                    .map(item -> {
                        String fullShortUrl = (String) item;
                        String[] split = fullShortUrl.split("/");
                        if (split.length == 2) return split[1];
                        return null;
                    }).filter(item -> !Objects.isNull(item))
                    .forEach(item -> {
                        bloomFilter.add(item);
                    });
        }
        catch (Exception e) {
            log.error("addDataToBloomFilter error: {}", e.getMessage());
        }
    }

    @Scheduled(cron = "00 35 23 L * ?")
    @Async("taskThreadPool")
    void clearUserBloomFilter() {
        try {
            stringRedisTemplate.delete("user");
        }
        catch (Exception e) {
            log.error("clearUserBloomFilter error: {}", e.getMessage());
        }
    }
}
